apackage com.jiuyun.auth.servlet;

import com.alibaba.druid.support.spring.stat.SpringStatUtils;
import com.jiuyun.auth.dao.RoleDao;
import com.jiuyun.auth.dao.impl.RoleDaoImpl;
import com.jiuyun.auth.entity.Role;
import com.jiuyun.auth.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

@WebServlet("/role/*")
public class RoleServlet extends BaseServlet {

    RoleDao roleDao = new RoleDaoImpl();

    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //显示角色授权页
        try {
            List list = roleDao.Rolefind();//所有角色
            System.out.println(list);
            request.setAttribute("roles",list);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        request.getRequestDispatcher("/role.jsp").forward(request,response);
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //给用户增加角色
        String roles[] = request.getParameterValues("myrole");
        System.out.println(Arrays.toString(roles));

       HttpSession session = request.getSession();
        User user = (User) session.getAttribute("LOGIN");
        int uid = user.getUid();
        try {
            roleDao.delRoles(uid);//删除用户角色
            if(roles!=null){
                for (String rid:roles){
                    roleDao.addRole(uid,Integer.parseInt(rid));
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        response.sendRedirect("/auth/index.jsp");


    }
}
